import React, { useState, useEffect } from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Flex, message, Upload } from 'antd';
import type { GetProp, UploadProps } from 'antd';
import { MyUploadApi } from '../apis/MyUploadApi';

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

const getBase64 = (img: FileType, callback: (url: string) => void) => {
	const reader = new FileReader();
	reader.addEventListener('load', () => callback(reader.result as string));
	reader.readAsDataURL(img);
};

/**
 * 图片上传组件
 * @param {Object} props - 组件属性
 * @param {string} props.id - 组件ID
 * @param {Function} props.onChange - 上传成功后的回调函数
 * @param {string} props.value - 当前图片URL值，用于外部控制显示和清空
 */
const MyUpload = (props: { id: string; onChange: (value: string) => void; value: string }) => {
	const [loading, setLoading] = useState(false);
	const [imageUrl, setImageUrl] = useState<string>();

	// 监听value属性变化，实现外部控制清空
	useEffect(() => {
		console.log(props.value);

		setImageUrl(props.value);
	}, [props.value]);

	/**
	 * 处理文件上传变化
	 * @param {Object} info - 上传信息对象
	 */
	const handleChange: UploadProps['onChange'] = async (info) => {
		// 处理上传中状态
		if (info.file.status === 'uploading') {
			setLoading(true);
			return;
		}

		// 处理上传完成状态
		if (info.file.status === 'done') {
			// 显示本地预览图
			getBase64(info.file.originFileObj as FileType, (url) => {
				setImageUrl(url);
			});

			try {
				// 准备上传数据
				const formData = new FormData();
				formData.append('file', info.file.originFileObj as FileType);

				// 调用上传API
				const res = await MyUploadApi(formData);
				// 通知父组件上传成功，传递图片URL
				props.onChange(res.data.url);
			} catch (error) {
				// 处理上传错误
				console.log(error);

				message.error('上传失败，请重试');
			} finally {
				// 无论成功失败，都要设置loading为false
				setLoading(false);
			}
		}

		// 处理上传失败状态
		if (info.file.status === 'error') {
			setLoading(false);
			message.error('上传失败，请重试');
		}
	};

	const uploadButton = (
		<button style={{ border: 0, background: 'none' }} type='button'>
			{loading ? <LoadingOutlined /> : <PlusOutlined />}
			<div style={{ marginTop: 8 }}>Upload</div>
		</button>
	);

	return (
		<span id={props.id}>
			<Flex gap='middle' wrap>
				<Upload
					name='avatar'
					listType='picture-card'
					className='avatar-uploader'
					showUploadList={false}
					action='http://47.113.230.113:8088/eduoss/fileoss'
					onChange={handleChange}
				>
					{imageUrl ? <img src={imageUrl} alt='avatar' style={{ width: '100%' }} /> : uploadButton}
				</Upload>
			</Flex>
		</span>
	);
};

export default MyUpload;
